<template>
  <el-card>
    <el-row slot="header">
      <el-col :span="12">{{ title }}</el-col>
      <el-col :span="12" style="text-align: right;">
        <el-button type="primary" @click="edit">编辑</el-button>
        <el-button :disabled="isInit == false" type="success" @click="generate">生成视图</el-button>
      </el-col>
    </el-row>
    <w-table
      :data="rows"
      :columns="columns"
      :is-paging="true"
      :paging="paging"
      @load="load"
    />
    <editView :visible.sync="visible" :form-id="formId" @close="refresh" />
  </el-card>
</template>

<script>
import moment from 'moment'
import * as formApi from '@/customForm/api/form'
import * as viewApi from '@/customForm/api/formView'
import editView from './editView.vue'
export default {
  components: {
    editView
  },
  data() {
    return {
      title: null,
      formId: null,
      visible: false,
      columns: [],
      rows: [],
      isGenerate: false,
      isInit: false,
      paging: {
        Size: 20,
        Index: 1,
        SortName: null,
        IsDesc: false,
        Total: 0
      }
    }
  },
  computed: {},
  mounted() {
    this.formId = this.$route.params.id
    if (this.formId == null) {
      return
    }
    this.initForm()
    this.initView()
  },
  methods: {
    moment,
    edit() {
      this.visible = true
    },
    refresh(isRefresh) {
      if (isRefresh) {
        this.initView()
      }
    },
    async generate() {
      await viewApi.Generate(this.formId)
      this.isGenerate = true
      this.load()
    },
    async initForm() {
      const res = await formApi.Get(this.formId)
      this.title = '编辑视图-' + res.FormName
    },
    async load() {
      if (this.isGenerate === false) {
        this.paging.Total = 0
        this.rows = []
        return
      }
      const res = await viewApi.Query(this.formId, this.paging)
      this.rows = res.List ?? []
      this.paging.Total = res.Count
    },
    async initView() {
      const res = await viewApi.GetBody(this.formId)
      if (res == null) {
        this.isGenerate = false
        this.isInit = false
        this.columns = []
        this.rows = []
        return
      }
      this.isGenerate = res.IsGenerate
      if (res.Cols && res.Cols.length > 0) {
        this.isInit = true
        this.columns = res.Cols.map(c => {
          return {
            key: c.Name,
            title: c.Label,
            align: 'center',
            minWidth: 120
          }
        })
        this.paging.Index = 1
        this.load()
      } else {
        this.isInit = false
        this.columns = []
      }
    }
  }
}
</script>
